package com.blank.shop.security.authentication;

import lombok.Getter;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.Objects;

/**
 * <br/>Date 2021/9/10
 * <br/>Time 4:01:21
 *
 * @author _blank
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    @Getter
    @Setter
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        final SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        final UserDetails userDetails = this.userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());

        if (Objects.isNull(userDetails)) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }

        final SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails.getAuthorities(), userDetails);

        authenticationResult.setDetails(authenticationToken.getDetails());


        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
